﻿using Loogn.OrmLite;
using SchedulerLite.Model.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SchedulerLite.DAL
{
    public class D_DelayTask
    {
        public static long Add(DelayTask m)
        {
            using (var db = DB.Open())
            {
                return db.Insert(m);
            }
        }

        public static long Update(DelayTask m)
        {
            using (var db = DB.Open())
            {
                return db.Update(m, "Name", "Url", "Method", "PostData", "Enable", 
                    "TriggerTime", "MaxRetryCount", "RetrySeconds", "SuccessFlag", "TimeoutSeconds");
            }
        }

        public static OrmLitePageResult<DelayTask> SearchList(string name, int pageIndex, int pageSize)
        {
            var condition = "1=1";
            name = SqlInjection.Filter(name);
            if (!string.IsNullOrEmpty(name))
            {
                condition += " and Name like '" + name + "'";
            }
            using (var db = DB.Open())
            {
                return db.SelectPage<DelayTask>(new OrmLitePageFactor
                {
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    OrderBy = "id desc",
                    Conditions = condition,
                });
            }
        }

        public static DelayTask SingleById(long id)
        {
            using (var db = DB.Open())
            {
                return db.SingleById<DelayTask>(id);
            }
        }

        public static int Delete(long id)
        {
            using (var db = DB.Open())
            {
                return db.DeleteById<DelayTask>(id);
            }
        }

        public static List<DelayTask> SelectReadyList(DateTime beginTime, DateTime endTime)
        {
            using (var db = DB.Open())
            {
                var sql = string.Format("select Id, TriggerTime from DelayTask WHERE Enable=1 and TriggerTime >= '{0}' AND TriggerTime<'{1}'", beginTime.ToString("yyyy-MM-dd HH:mm:ss"), endTime.ToString("yyyy-MM-dd HH:mm:ss"));
                //Console.WriteLine(sql);
                return db.Select<DelayTask>(sql);
            }
        }

        public static List<DelayTask> SelectByIds(List<long> ids)
        {
            using (var db = DB.Open())
            {
                return db.SelectByIds<DelayTask>(ids);
            }
        }

        public static int RetryUpdate(DelayTask task)
        {
            using (var db = DB.Open())
            {
                var flag = db.Update<DelayTask>(DictBuilder
                    .Assign("TriggerTime", task.TriggerTime)
                    .Assign("$RetryCount", "RetryCount+1")
                    .Assign("$ExecCount", "ExecCount+1"), "Id=" + task.Id, null);
                return flag;
            }
        }
    }
}
